//
//  BKComposePictureView.swift
//  微博
//
//  Created by mac on 16/8/17.
//  Copyright © 2016年 xbk. All rights reserved.
//

import UIKit

let BKComposePictureViewIdentifier = " BKComposePictureViewIdentifier"

class BKComposePictureView: UICollectionView {
    
    //点击加号执行的闭包
    var didSelectAddImageViewClosure:(()->())?

    
    lazy var images:[UIImage] = [UIImage]()

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let flowLayout = UICollectionViewFlowLayout()
        
        super.init(frame: frame, collectionViewLayout: flowLayout)
        setupUI()
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
    
        dataSource = self
        delegate = self
        //注册cell
        registerClass(BKComposePictureViewCell.self, forCellWithReuseIdentifier: BKComposePictureViewIdentifier)
    }
    
    //添加图片
    func addImage(image:UIImage){
        
        if images.count > 9 {
        
            return
        }
    
        images.append(image)
        self.reloadData()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        let itemMargin :CGFloat = 5
        let itemWidth:CGFloat = (width - 2 * itemMargin)/3
        
        //获取布局方式
        let flowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout
        //设置大小
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        flowLayout.minimumLineSpacing = itemMargin
        flowLayout.minimumInteritemSpacing = itemMargin
    }
    

}

// MARK: -- UICollectionView的代理方法
extension BKComposePictureView:UICollectionViewDataSource,UICollectionViewDelegate{

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        if images.count == 0 || images.count == 9{
        
            return images.count
            
        }else{
        
            return images.count + 1
        }
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(BKComposePictureViewIdentifier, forIndexPath: indexPath) as!BKComposePictureViewCell
        
        //如果先添加一张图片,这时候cell的个数是2,当是第0个cell时,向cell添加图片.当是第1个cell的时候正好和image数组的长度相等,这时候设置cell.image = nil,用来防止数组越界
        //  indexPath.item索引等于数组的个数表示最后一个cell
        if indexPath.item == images.count{
        
            cell.image = nil
        }else{
            //绑定图片
            cell.image = images[indexPath.item]
            
            //删除图片
            cell.deleteImageClosure = {[weak self] in
            
                self?.images.removeAtIndex(indexPath.item)
                
                self?.reloadData()
            }
        }
        
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        if indexPath.item == images.count {
        
            collectionView.deselectItemAtIndexPath(indexPath, animated: true)
            didSelectAddImageViewClosure?()
        }
    }
}

// MARK: -- 自定义cell
class BKComposePictureViewCell:UICollectionViewCell{
    
    //删除选中图片的闭包
    var deleteImageClosure:(()->())?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    

    //懒加载创建控件
    private lazy var imageView:UIImageView = UIImageView()
    
    private lazy var deleteButton:UIButton = {
    
        let button = UIButton()
        button.setImage(UIImage(named: "compose_photo_close"), forState: .Normal)
        button.addTarget(self, action: "deleteButtonAction", forControlEvents: .TouchUpInside)
        return button
    }()
    
    //设置约束
    private func setupUI() {
    
        contentView.addSubview(imageView)
        contentView.addSubview(deleteButton)
        
        imageView.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        
        deleteButton.snp_makeConstraints { (make) -> Void in
            
            make.top.equalTo(imageView)
            make.trailing.equalTo(imageView)
        }
    }
    
    @objc private func deleteButtonAction(){
    
        //print("ssss")
       deleteImageClosure?()
    }
    
    var image:UIImage? {
    
        didSet{
            
            if image == nil{
                deleteButton.hidden = true
                imageView.image = UIImage(named: "compose_pic_add")
                imageView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
            }else{
            
                imageView.image = image
                
                deleteButton.hidden = false
                imageView.highlightedImage = nil
            }
        
        }
    }
    
}




